package com.qd.flow.service.workbench;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qd.common.flow.constant.FlowConstants;
import com.qd.common.flow.domain.bill.FlowBillDTO;
import com.qd.common.flow.domain.bill.FlowQueryDTO;
import com.qd.common.flow.domain.index.IndexDTO;
import com.qd.common.flow.domain.index.ProcessCountDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.flow.model.bill.FlowBill;
import com.qd.flow.service.bill.FlowBillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjk
 * @create 2024-02-26 12:51
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WorkbenchService {

    private final FlowBillService flowBillService;

    @Transactional(readOnly = true)
    public IndexDTO index() {
        IndexDTO indexDTO = new IndexDTO();
        buildCompletedTask(indexDTO);
        buildToDoTask(indexDTO);
        return indexDTO;
    }

    @Transactional(readOnly = true)
    public IPage<FlowBillDTO> toDoTaskPage(Page<FlowBill> page, FlowQueryDTO dto) {
        dto.setBillState(FlowConstants.BILL_STATE_0);
        dto.setApprovalDepart(SecurityUtils.getLoginUser().getCurrentOrgId());
        return flowBillService.toDoTaskPage(page, dto);
    }

    @Transactional(readOnly = true)
    public IPage<FlowBillDTO> completedTaskPage(Page<FlowBill> page, FlowQueryDTO dto) {
        dto.setBillState(FlowConstants.BILL_STATE_1);
        dto.setApprovalDepart(SecurityUtils.getLoginUser().getCurrentOrgId());
        return flowBillService.completedTaskPage(page, dto);
    }


    private void buildCompletedTask(IndexDTO indexDTO) {
        Long completedTaskNum = flowBillService.hisTaskCount(SecurityUtils.getLoginUser().getCurrentOrgId(), null);
        indexDTO.setCompletedTaskCount(Optional.ofNullable(completedTaskNum).orElse(0L));
    }

    private void buildToDoTask(IndexDTO indexDTO) {
        List<ProcessCountDTO> countList = flowBillService.countByProcessId(SecurityUtils.getLoginUser().getCurrentOrgId());
        long toDoTaskNum = 0L;
        if(null != countList && !countList.isEmpty()){
            toDoTaskNum = countList.stream().mapToLong(ProcessCountDTO::getCount).sum();
        }
        indexDTO.setToDoTaskCount(toDoTaskNum);
    }

}